<template>
  <view class="container">
    <!-- 头部导航 -->
    <PageHeader title='设置登录密码' :showBack="true" />
    <!-- <view class="header flex items-center justify-between p-[32rpx] border-b border-gray-100 bg-white">
      <IconFont
        name="arrow-left"
        size="32rpx"
        class="text-gray-600"
        @click="goBack"
      />
      <text class="text-[36rpx] font-bold text-gray-800">设置登录密码</text>
      <view class="w-[32rpx]"></view>
    </view> -->

    <!-- 表单区域 -->
    <view class="form-container p-[32rpx] bg-white rounded-24rpx shadow-lg mt-6">
      <nut-form :model="formData" ref="formRef">
        <!-- 设置密码 -->
        <view class="mb-6">
          <view class="relative" :style="{ display: 'flex' }">
            <nut-input v-model="formData.newPassword" :type="newPasswordVisible ? 'text' : 'password'"
              placeholder="请设置密码（至少6位）" placeholder-class="text-gray-400"
              class="w-full h-[88rpx] px-4 border border-gray-200 rounded-16rpx text-[28rpx]"
              @blur="validateField('newPassword')" />
            <IconFont :name="newPasswordVisible ? 'eye-open' : 'eye-close'" size="32"
              class="text-gray-400 absolute right-4 top-0 bottom-0 m-auto"
              @click="togglePasswordVisibility('newPassword')" />
          </view>
          <!-- 错误提示 -->
          <text v-if="errors.newPassword" class="text-red-500 text-[24rpx] mt-2 block">{{ errors.newPassword }}</text>
        </view>

        <!-- 确认密码 -->
        <view class="mb-8">
          <view class="relative" :style="{ display: 'flex' }">
            <nut-input v-model="formData.confirmPassword" :type="confirmPasswordVisible ? 'text' : 'password'"
              placeholder="请再次输入密码" placeholder-class="text-gray-400"
              class="w-full h-[88rpx] px-4 border border-gray-200 rounded-16rpx text-[28rpx]"
              @blur="validateField('confirmPassword')" />
            <IconFont :name="confirmPasswordVisible ? 'eye-open' : 'eye-close'" size="32"
              class="text-gray-400 absolute right-4 top-0 bottom-0 m-auto"
              @click="togglePasswordVisibility('confirmPassword')" />
          </view>
          <!-- 错误提示 -->
          <text v-if="errors.confirmPassword" class="text-red-500 text-[24rpx] mt-2 block">{{ errors.confirmPassword
          }}</text>
        </view>

        <!-- 提交按钮 -->
        <view class="mt-[60rpx] px-[30rpx]">
          <nut-button type="primary" size="large" :loading="submitting" @click="submitForm"
            class="h-[88rpx] rounded-[44rpx] text-[32rpx] bg-green-500">
            确认
          </nut-button>
        </view>
      </nut-form>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import Taro, { showToast } from "@tarojs/taro";
import { Form, Input, Button } from "@nutui/nutui-taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post } from "@/utils/request";
import PageHeader from '@/components/PageHeader.vue'
import { useUserStore } from "@/store/user";

const userStore = useUserStore();

// 表单数据
const formData = reactive({
  newPassword: "",
  confirmPassword: ""
});

// 错误信息存储
const errors = reactive({
  newPassword: "",
  confirmPassword: ""
});

// 密码可见性
const newPasswordVisible = ref(false);
const confirmPasswordVisible = ref(false);

// 提交状态
const submitting = ref(false);
const formRef = ref(null);

// 返回上一页
const goBack = () => {
  Taro.navigateBack({
    delta: 1,
  });
};

// 获取路由上的参数
const urlId = Taro.getCurrentInstance().router?.params?.id
console.log(urlId)

// 切换密码可见性
const togglePasswordVisibility = (type) => {
  switch (type) {
    case "newPassword":
      newPasswordVisible.value = !newPasswordVisible.value;
      break;
    case "confirmPassword":
      confirmPasswordVisible.value = !confirmPasswordVisible.value;
      break;
  }
};

// 表单校验规则
const rules = {
  newPassword: [
    { required: true, message: "请设置密码" },
    { min: 6, message: "密码不能少于6位" }
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码" },
    {
      validator: (value) => {
        return value === formData.newPassword || "两次输入的密码不一致";
      }
    }
  ]
};

// 验证单个字段
const validateField = (field) => {
  const ruleList = rules[field];
  if (!ruleList) return true;

  for (const rule of ruleList) {
    // 必填验证
    if (rule.required && !formData[field]) {
      errors[field] = rule.message;
      return false;
    }
    // 长度验证
    if (rule.min && formData[field].length < rule.min) {
      errors[field] = rule.message;
      return false;
    }
    // 自定义验证器
    if (rule.validator) {
      const result = rule.validator(formData[field]);
      if (result !== true) {
        errors[field] = result;
        return false;
      }
    }
  }

  // 验证通过清空错误
  errors[field] = "";
  return true;
};

// 整体表单验证
const validateForm = () => {
  let isValid = true;
  Object.keys(rules).forEach(field => {
    if (!validateField(field)) {
      isValid = false;
    }
  });
  return isValid;
};

// 提交表单
const submitForm = async () => {
  // 执行表单验证
  if (!validateForm()) {
    return;
  }

  submitting.value = true;

  try {
    if(formData.newPassword == formData.confirmPassword){
      // 调用API初始化密码
      const res = await post("/user/initPassword", {
        password: formData.confirmPassword
      });
      if (res.code === 0) {
        showToast({
          title: "密码设置成功",
          icon: "success"
        });
        userStore.userInfo.password = '1'
        // 延迟后返回上一页
        setTimeout(() => {
          Taro.navigateBack({
            delta: 2,
          });
        }, 1500);
      }else{
        showToast({
          title: res.message || "设置失败，请重试",
          icon: "none"
        });
      }
    }else{
      showToast({
        title: "两次输入的密码不一致",
        icon: "none"
      });
      formData.newPassword = ''
      formData.confirmPassword = ''
    }
  } catch (error) {
    showToast({
      title: "网络错误，请稍后再试",
      icon: "none"
    });
  } finally {
    submitting.value = false;
  }
};
</script>

<style lang="scss">
.container {
  width: 750rpx;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.shadow-lg {
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.rounded-16rpx {
  border-radius: 16rpx;
}

.rounded-24rpx {
  border-radius: 24rpx;
}

.mt-6 {
  margin-top: 24rpx;
}

.mb-6 {
  margin-bottom: 24rpx;
}

.mb-8 {
  margin-bottom: 32rpx;
}

.border-gray-200 {
  border-color: #EBEEF5;
}

.text-red-500 {
  color: #F56C6C;
}

.bg-green-500 {
  background-color: #00B42A;
}
</style>